import axios from "axios";
import store from "../store";
import { nException, nSuccess } from "../components/TipsDialog";
import SafeCall from "../utils/SafeCall.js";
import Notify from "../components/TipsDialog";

const instance = axios.create({
    timeout: 30000
})
instance.interceptors.request.use(config => {
    Object.assign(config.headers, { 'token': store.token })
    return config
})

const apis = {
    host: "http://192.168.1.130",
    static: "http://192.168.1.130:6660",
    login: (username, password) => instance.post("/api/login", { username, password }),
    register: (email, password, captcha) => instance.post("/api/user", { email, password, captcha }),
    forgetPassword: (username, password, captcha) => instance.post("/api/user/forget", { username, password, captcha }),
    getCaptcha: (email) => instance.post("/api/user/captcha", { email }),
    getUserById: (userid) => instance.get("/api/user/" + userid),
    preSaveFile: (md5, filename) => instance.post("/api/file/pre", { md5, filename }),
    saveFile: (data, onUploadProgress) => instance.post("/api/file/save", data, { onUploadProgress }),
    createShareKey: (md5) => instance.post(`/api/file/share/${md5}`),
    download: (key, filename) => instance.post(`/api/download/${key}`, { filename }, { responseType: 'blob' }),
    getAllFile: () => instance.post("/api/file"),
    getAllImage: () => instance.post("/api/image"),
    getAllMusic: () => instance.post("/api/music"),
    getAllVideo: () => instance.post("/api/video"),
    getAllArticle: () => instance.post("/api/article"),
    getImageById: (id) => instance.post(`/api/image/public/${id}`),
    getMusicById: (id) => instance.post(`/api/music/public/${id}`),
    getVideoById: (id) => instance.post(`/api/video/public/${id}`),
    getArticleById: (id) => instance.post(`/api/article/public/${id}`),
    deleteImageById: (id) => instance.delete(`/api/image/${id}`),
    deleteMusicById: (id) => instance.delete(`/api/music/${id}`),
    deleteVideoById: (id) => instance.delete(`/api/video/${id}`),
    deleteArticleById: (id) => instance.delete(`/api/article/${id}`),
    getAllPublicFile: () => instance.get("/api/file/public"),
    getAllPublicArticle: () => instance.get("/api/article/public"),
    setPublicToFileById: (id, setpublic) => instance.post("/api/file/public", { id, setpublic }),
    setPublicToArticleById: (id, setpublic) => instance.post("/api/article/public", { id, setpublic }),
    saveArticle: (title, content) => instance.post("/api/article/save", { title, content }),
    checkLogined: () => {
        return store.token != null && store.token != ''
    },
    checkBelongTo: (uid) => {
        if (store.token == null || store.token == '')
            return false
        if (store.userInfo.uid == null || store.userInfo.uid == '')
            return false
        return store.userInfo.uid == uid
    },
    checkLogin: (next, notify, param) => {
        if (store.token != null && store.token != '') {
            next(param)
            return
        }
        Notify(notify)
        next('/login')
    }
}

/**
 *  通用的promise处理函数，成功和失败都弹出对应的弹窗和信息
 *  附带有onSuccess和onFailed两个钩子函数 
 *
 * @param promise {Promise}
 * @param onSuccess {Function?}
 * @param onFailed {Function?}
 */
const tipsPromiseHandler = (promise, onSuccess, onFailed) => {
    promise.then(response => response?.data).then(data => {
        SafeCall(onSuccess, data)
        nSuccess(data['message'] || '请求成功')
    }).catch(error => {
        let data = error.response?.data
        SafeCall(onFailed, data)
        nException(data?.message || '请求失败')
    })
}

export { apis, instance, tipsPromiseHandler }
export default instance